package com.globallogic.javatrainings.sergiiivanov.model;

import java.io.Serializable;

/**
 * Implements typical LIFO stack<br>
 * Based on {@link MyArray}<br>
 * Used in Controllers to keep queue of called sub-controllers.
 * 
 * @author Sergey
 * 
 * @param <T>
 *            - type of stack
 */
public class MyStack<T> implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private MyArray<T> stack;

    /**
     * Creates new stack for storing instances of T
     * 
     * @param initialArray
     *            - array T[] could be provided as initial content<br>
     * @see MyArray#MyArray(Object[])
     */
    public MyStack(T[] initialArray) {
        stack = new MyArray<T>(initialArray);
    }

    /**
     * Adds element on the top of stack
     * 
     * @param o
     *            - instance of T to add
     */
    public void push(T o) {
        stack.add(o);
    };

    /**
     * Returns top element from stack or null, when stack is empty<br>
     * Top element is removed and previously added element come on top
     * 
     * @return top element as instance of T
     */
    public T pop() {
        T result = null;
        try {
            result = stack.get(stack.size() - 1);
            stack.remove(stack.size() - 1);
        } catch (UniversityFailure e) {}
        return result;
    };

    /**
     * Calculates number of elements in the stack
     * 
     * @return number of elements
     */
    public int size() {
        return stack.size();
    }

}
